package com.dzh.xdyy;
import android.Manifest;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.baidu.speech.EventManager;
import com.baidu.speech.EventManagerFactory;
import com.baidu.speech.asr.SpeechConstant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    public final static String TAG="Main-----";
    EventManager wakeup;//唤醒
    EventManager asr;//识别
    private boolean lock = true; //为false时不再启动语音唤醒

    private VideoView videoView;
    private SpeechUtils speech;
    private int vid=1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        //getActionBar().hide();
        setContentView(R.layout.activity_main);
        initPermission();//6.0才用动态权限
        speech=SpeechUtils.getInstance(this);

        String path=getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString();
        deposit(path,"1.mp4");
        deposit(path,"2.mp4");
        //使用VideoView播放视频
        VideoView videoView = (VideoView)findViewById(R.id.videoView);
        videoView.setVideoURI(Uri.parse(path+"/"+vid+".mp4"));
        MediaController mediaCtlr = new MediaController(this);//创建MediaController对象
        mediaCtlr.setVisibility(View.VISIBLE);//View.INVISIBLE
        videoView.setMediaController(mediaCtlr);
        videoView.setOnCompletionListener((mp)-> {
            //if(vid==1){vid=2;}else{vid=1;}
            videoView.setVideoURI(Uri.parse(path+"/"+vid+".mp4"));
            videoView.start();
        });
        videoView.setOnPreparedListener((mp)-> {
            mp.setVolume(0f, 0f);
            mp.start();
        });
        videoView.requestFocus();

        TextView txt1=(TextView) findViewById(R.id.txt1);

        Toast.makeText(MainActivity.this,"准备唤醒",Toast.LENGTH_LONG).show();
        wakeup = EventManagerFactory.create(this, "wp");
        wakeup.registerListener((name,params,data,offset,length)->{//唤醒
            if(name.equals("wp.data")){
                try {
                    JSONObject json = new JSONObject(params);
                    int errorCode = (int)json.get("errorCode");
                    if(errorCode == 0){
                        Mp3Util.reset();
                        speech.speak("我在");
                        Log.d(TAG,"唤醒成功:"+json.get("word"));
                        new Handler().postDelayed(()->{
                            start();//语音识别
                        }, 1500);//1.5秒后执行Runnable中的run方法
                    } else {
                        Log.d(TAG,"唤醒失败");
                    }
                }catch (JSONException e){

                }

            } else if("wp.exit".equals(name)){
                Log.d(TAG,"唤醒停止");
            }
        }); //  EventListener 中 onEvent方法
        Toast.makeText(MainActivity.this,"准备识别",Toast.LENGTH_LONG).show();
        asr = EventManagerFactory.create(this, "asr");
        asr.registerListener((String name, String params, byte [] data, int offset, int length)->{
            if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {
                if (params == null || params.isEmpty()) {
                    return;
                }
                if (params.contains("\"final_result\""))  {

                    try {
                        JSONObject json = new JSONObject(params);
                        System.out.println(json);
                        JSONArray sps= json.getJSONArray("results_recognition");
                        String anw=sps.getString(0);
                        String anw1=anw;
                        txt1.setText(anw);
                        new Thread() {
                            public void run() {//这儿是耗时操作，完成之后更新UI；
                                if(anw1.contains("儿歌")){
                                    int i1= (int)(1+Math.random()*(10));//1-10
                                    Mp3Util.play(getAssets(),"儿歌/"+i1+".mp3");
                                    return;
                                }else if(anw1.contains("歌曲")||anw1.contains("首歌")||anw1.contains("音乐")
                                        ||anw1.contains("来首")||anw1.contains("一首")){
                                    int i1= (int)(1+Math.random()*(21));//1-11
                                    Mp3Util.play(getAssets(),"歌曲/"+i1+".mp3");
                                    return;
                                }else if(anw1.contains("故事")){
                                    int i1= (int)(1+Math.random()*(11));//1-11
                                    Mp3Util.play(getAssets(),"故事/"+i1+".mp3");
                                    return;
                                }
                                String jieguo=Robot.aibot(anw1);
                                //Toast.makeText(MainActivity.this,jieguo,Toast.LENGTH_LONG).show();
                                if(jieguo.startsWith("[")||jieguo.startsWith("{")){
                                    jieguo="暂不支持该类型的消息!";
                                }

                                String jieguo1=jieguo;
                                runOnUiThread(()->{
                                    txt1.setText(jieguo1);
                                    speech.speak(jieguo1);
                                });
                            }
                        }.start();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }
        });
        Toast.makeText(MainActivity.this,"好了",Toast.LENGTH_LONG).show();
        new Handler().postDelayed(()->{
            startWakeUp();

        }, 1000);//2秒后执行Runnable中的run方法

    }

    /**
     * 基于SDK集成2.2 发送开始事件
     */
    private void start() {
        if(lock==false){
            return;
        }
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put(SpeechConstant.APP_ID, "28000965");
        params.put(SpeechConstant.APP_KEY, "u0ap6VP9CxAy5ifFE7uhGGEm");
        params.put(SpeechConstant.SECRET, "i10NhSuil2iTdvdKAMPe93sWnzWMT84y");
        params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);//设置识别参数
        asr.send(SpeechConstant.ASR_START,new JSONObject(params).toString(), null, 0, 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        wakeup.send(SpeechConstant.WAKEUP_STOP, "{}", null, 0, 0);
    }
    /**
     * 停止识别 基于SDK集成4.1 发送停止事件
     */
    private void stop() {
        lock = false; //不再识别
        asr.send(SpeechConstant.ASR_STOP, null, null, 0, 0); //
    }

    private void startWakeUp() {
        Map<String, Object> params = new LinkedHashMap<String, Object>();
        params.put(SpeechConstant.APP_ID, "28000965");
        params.put(SpeechConstant.APP_KEY, "u0ap6VP9CxAy5ifFE7uhGGEm");
        params.put(SpeechConstant.SECRET, "i10NhSuil2iTdvdKAMPe93sWnzWMT84y");
        params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME, false);
        params.put(SpeechConstant.WP_WORDS_FILE, "assets://WakeUp.bin");
        String json = new JSONObject(params).toString();
        wakeup.send(SpeechConstant.WAKEUP_START, json, null, 0, 0);
        Log.d(TAG,"输入参数：" + json);
    }

    private void stopWakeUp() {
        lock = false; //不再识别
        wakeup.send(SpeechConstant.WAKEUP_STOP, null, null, 0, 0); //
    }

    //将assets内文件存储到本地下载目录
    public Boolean deposit(String path,String fileName){
        InputStream inputStream;
        try {

            //判断文件是否存在
            File file1=new File(path + "/" + fileName);

            if(!file1.exists()){

                inputStream=getAssets().open(fileName);
                File file = new File(path);
                //当目录不存在时创建目录
                if(!file.exists()){
                    file.mkdirs();
                }

                FileOutputStream fileOutputStream = new FileOutputStream(path + "/" + fileName);// 保存到本地的文件夹下的文件
                byte[] buffer = new byte[1024];
                int count = 0;
                while ((count = inputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, count);
                }
                fileOutputStream.flush();
                fileOutputStream.close();
                inputStream.close();

            }else {
                Toast.makeText(MainActivity.this,"已存在",Toast.LENGTH_LONG).show();

            }

            return true;


        }catch (IOException e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * android 6.0 以上需要动态申请权限
     */
    private void initPermission() {
        String permissions[] = {
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.WAKE_LOCK,
                Manifest.permission.RECEIVE_BOOT_COMPLETED,
                Manifest.permission.INTERNET
        };
        ArrayList<String> toApplyList = new ArrayList<String>();
        for (String perm :permissions){
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                //进入到这里代表没有权限.

            }
        }
        String tmpList[] = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()){
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // 此处为android 6.0以上动态授权的回调，用户自行实现。
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }
}